<template>
  <div class="all-content">
    <BreadList modelName="任务管理" :breadList="breadList"></BreadList>
    <div class="manage-content"
      v-loading="listLoading"
      element-loading-text="加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.5)">
      <div class="page-title">
        <p>{{ activeItem.name }}</p>
      </div>
      <div class="search-content">
        <div class="search-item">时间
          <el-date-picker
            class="item-time"
            v-model="searchParams.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </div>
        <div class="search-item">状态
          <el-select 
            v-model="searchParams.state"
            placeholder="请选择状态"
            class="item-select">
            <el-option
              v-for="item in stateColorList"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </div>
        <el-button class="search-btn" type="primary" @click="getTableList(1, true)">搜索</el-button>
        <el-button class="search-btn" @click="clearSearch">重置</el-button>
      </div>
      <div class="table-content">
        <div class="list" v-show="tableData.length > 0">
          <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%;height: 100%"
            height="100%">
            <el-table-column
              label="序号"
              type="index"
              width="68">
              <template slot-scope="scope">
                <span>{{(tablePageData.currentPage - 1) * tablePageData.pageSize + scope.$index + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="taskRunStartTime"
              label="日期">
            </el-table-column>
            <el-table-column
              prop="behavior"
              :formatter="behaviorFormatter"
              label="行为">
            </el-table-column>
            <el-table-column
              label="状态">
              <template slot-scope="scope">
                <span :style="{'color': scope.row.statusColor}">{{scope.row.statusName}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="exceptionNum"
              label="筛查异常数"
              width="120">
              <template slot-scope="scope">
                <span>{{scope.row.behavior === 1 ? '-' : scope.row.exceptionNum}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="145">
              <template slot-scope="scope">
                <span
                  v-if="buttonList.some(item => item.value === '/TaskList/view')"
                  :class="['operate-item', {'disabled': scope.row.status === 3 || scope.row.status === 5 || (scope.row.status === 1 && !scope.row.isLast)}]"  
                  @click="itemLook(scope.row)">
                  <span class="icon icon-look"></span>
                  查看
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page-box" v-show="tableData.length > 0">
          <el-pagination
            class="table-page"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="tablePageData.currentPage"
            :page-sizes="tablePageData.pageSizes"
            :page-size="tablePageData.pageSize"
            background
            layout="total, sizes, slot, prev, pager, next"
            :total="tablePageData.total">
            <span class="page-item first" @click="handleCurrentChange(1)">首页</span>
          </el-pagination>
          <el-pagination
            class="table-page"
            @current-change="handleCurrentChange"
            :current-page="tablePageData.currentPage"
            :page-sizes="tablePageData.pageSizes"
            :page-size="tablePageData.pageSize"
            background
            layout="slot"
            :total="tablePageData.total">
            <span class="page-item" @click="handleCurrentChange(Math.ceil(tablePageData.total/tablePageData.pageSize))">末页</span>
            <span class="page-jumper">跳至<el-input class="page-num" v-model="tablePageData.inputNum" @input.native="tablePageData.inputNum = JSON.stringify(tablePageData.inputNum).replace(/[^0-9]/g,'')" @blur="handleCurrentChange(tablePageData.inputNum)" @keyup.enter.native="handleCurrentChange(tablePageData.inputNum)"></el-input>页</span>
          </el-pagination>
        </div>
        <Empty v-show="tableData.length === 0" imgHeight="42%" />
      </div>
      <el-dialog
        title="详细信息"
        :visible.sync="infoModelShow"
        v-if="infoModelShow"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :append-to-body="false"
        width="560px">
          <div class="info-content" v-html="infoContent">{{infoContent}}</div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="infoModelShow = false">关闭</el-button>
          </span>
      </el-dialog>
      <el-dialog
        title="详细信息"
        :visible.sync="taskModelShow"
        v-if="taskModelShow"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :append-to-body="false"
        width="1008px">
          <!-- <div class="task-percent-title">
            整体任务进度
            <span>{{taskPercent + '%'}}</span>
          </div>
          <el-progress :stroke-width="16" status="success" :percentage="taskPercent" :show-text="false"></el-progress>
          <div class="info-content task-percent" v-html="taskContent">{{taskContent}}</div> -->
          <iframe class="info-content" :src="taskContent" :allowfullscreen="true"></iframe>
          <span slot="footer" class="dialog-footer">
            <el-button v-if="activeTaskStatus === 4" type="primary" @click="taskClose">终止任务</el-button>
            <el-button @click="taskModelShow = false">关闭</el-button>
          </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import Empty from '../../components/empty';
  import { TaskResource, config } from '../../axios/index';
  import { mapGetters, mapActions } from 'vuex';
  import BreadList from '../../components/breadList';
  export default {
    name: 'TaskList',
    components: {
      Empty,
      BreadList
    },
    data() {
      return {
        // 表格相关
        listLoading: false,
        tableData: [],
        tablePageData: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          pageSizes: [10, 20, 50],
          inputNum: 1
        },
        // 状态下拉数据
        stateList: [
          {
            code: 0,
            name: '全部'
          }
        ],
        // 搜索条件
        searchParams: {
          time: [],
          state: 0
        },
        oldSearchParams: {
          time: [],
          state: 0
        },
        // 状态颜色
        stateColorList: [
          {
            code: 0,
            name: '全部'
          },
          {
            name: '已完成',
            code: 5,
            color: '#3DC27C'
          },
          {
            name: '执行异常',
            code: 2,
            color: '#ED5861'
          },
          {
            name: '执行成功',
            code: 1,
            color: '#3DC27C'
          },
          {
            name: '任务中断',
            code: 3,
            color: '#F4A41A '
          },
          {
            name: '执行中',
            code: 4,
            color: '#3C86F5 '
          },
        ],
        // 查看日志
        infoModelShow: false,
        infoContent: '',
        // 查看任务进度
        taskModelShow: false,
        taskContent: '',
        taskPercent: 50,
        // 当前任务状态
        activeTaskStatus: null,
        activexxlLogId: null,
        // 面包屑
        breadList: [
          {
            modelName: 'ManageList',
            name: '任务管理'
          },
          {
            modelName: 'ManageList',
            name: '任务列表'
          }
        ]
      }
    },
    mounted() {
      this.getTableList();
      console.log(this.activeItem)
    },
    methods: {
      ...mapActions([
        'setActiveItem'
      ]),
      // 行为格式化
      behaviorFormatter(row) {
        switch(row.behavior){
          case 1:
            return '创建任务'
          case 2:
            return '执行任务'
          default:
            return ''
        }
      },
      // 获取列表数据
      getTableList(page, record) {
        if(page) {
          this.tablePageData.currentPage = page;
          this.tablePageData.inputNum = page;
        }
        if(record) {
          this.oldSearchParams = JSON.parse(JSON.stringify(this.searchParams));
        }
        let returnTrue = false;
        setTimeout(() => {
          if(!returnTrue) {
            this.listLoading = true;
          }
        }, 100)
        TaskResource
        .queryTaskLogListByID({
          id: this.activeItem.taskId,
          taskRunStartTimeBegin: this.searchParams.time && this.searchParams.time.length > 0 ? this.searchParams.time[0] + ' 00:00' : null,
          taskRunStartTimeEnd: this.searchParams.time && this.searchParams.time.length > 0 ? this.searchParams.time[1] + ' 23:59' : null,
          status: this.searchParams.state,
          pageNo: this.tablePageData.currentPage,
          pageSize: this.tablePageData.pageSize
        })
        .then(res => {
          returnTrue = true;
          this.listLoading = false;
          if(res && res.data) {
            this.tablePageData.total = parseInt(res.data.total);
            if(res.data.records) {
              this.tableData = res.data.records.map(item => {
                item.statusColor = item.status ? this.stateColorList.find(fitem => fitem.code === item.status).color : '';
                item.statusName = item.status ? this.stateColorList.find(fitem => fitem.code === item.status).name : '';
                return item
              });
            }
          }
        })
        .catch(() => {
          returnTrue = true;
          this.listLoading = false;
        })
      },
      // 改变每页size
      handleSizeChange(val) {
        this.tablePageData.pageSize = val;
        this.searchParams = JSON.parse(JSON.stringify(this.oldSearchParams));
        this.getTableList(1)
      },
      // 切页
      handleCurrentChange(val) {
        val = parseInt(val);
        if(!val || val <= 0) {
          val = 1;
        }
        else if(val > Math.ceil(this.tablePageData.total / this.tablePageData.pageSize)) {
          val = Math.ceil(this.tablePageData.total / this.tablePageData.pageSize);
        }
        this.tablePageData.inputNum = val;
        if(val === this.tablePageData.currentPage) {
          return
        }
        this.tablePageData.currentPage = val;
        this.searchParams = JSON.parse(JSON.stringify(this.oldSearchParams));
        this.getTableList();
      },
      // 重置
      clearSearch() {
        this.searchParams = {
          time: [],
          state: 0
        }
        this.getTableList(1, true);
      },
      // 查看任务
      itemLook(item) {
        this.activeTaskStatus = item.status;
        this.activexxlLogId = item.xxlLogId;
        // 任务中断/已完成，不可点击
        if(item.status === 5 || item.status === 3) {
          return
        }
        // 执行成功
        else if(item.status === 1) {
          // 同一个任务，运行多次，仅能看最后一次执行的结果，之前执行成功不给查看了
          // 不是最后一次执行结果
          if(!item.isLast) {
            return
          }
          // 无任何线索，提示未发现线索
          else if(!item.exceptionNum) {
            this.$message.warning('未发现线索');
          }
          // 进入任务详情页面
          else {
            let activeItem = this.activeItem;
            activeItem.detailId = item.id;
            activeItem.taskLogId = item.id;
            activeItem.clueName = item.clueName;
            this.setActiveItem(activeItem)
            this.$router.push({path:'/TaskDetails'})
          }
        }
        // 执行异常，查看异常日志
        // else if(item.status === 2) {
        //   this.infoModelShow = true;
        //   this.infoContent = '失败日志rdsfef<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe<br>fefefefefe'
        // }
        // 执行中，查看系统日志并可终止任务
        else if(item.status === 4 || item.status === 2) {
          this.taskModelShow = true;
          this.taskContent = config.logUrl + '?id=' + item.xxlLogId;
        }
      },
      // 终止任务
      taskClose() {
        TaskResource
        .killTask({
          xxlLogId: this.activexxlLogId
        })
        .then(res => {
          this.$message.success('终止任务成功');
          this.taskModelShow = false;
          this.searchParams = JSON.parse(JSON.stringify(this.oldSearchParams));
          this.getTableList();
        })
      }
    },
    computed: {
      ...mapGetters({
        activeItem: "getActiveItem",
        buttonList: "getButtonPermissions"
      })
    }
  }
</script>

<style scoped lang="scss">
  .all-content {
    width: 100%;
    height: 100%;
  }
  .manage-content {
    width: 100%;
    height: calc(100% - 32px);
    padding: 0 24px;
    background-color: #fff;
    .page-title {
      padding-left: 11px;
      font-size: 14px;
      font-family: PingFangSC, PingFangSC-Medium;
      font-weight: 500;
      color: #2d333c;
      line-height: 22px;
      padding-top: 18px;
      position: relative;
      &::before {
        display: block;
        content: '';
        width: 4px;
        height: 12px;
        background: #3c86f5;
        border-radius: 1px;
        position: absolute;
        left: 0;
        top: 23px;
      }
    }
    .table-content {
      height: calc(100% - 128px);
    }
    .info-content {
      width: 100%;
      height: 100%;
      padding: 16px;
      background: #F0F2F5;
      border-radius: 2px;
      border: 1px solid #DBDCE3;
      overflow: auto;
      line-height: 24px;
      color: #2D333C;
      font-size: 14px;
    }
    .task-percent-title {
      font-size: 16px;
      margin-bottom: 12px;
      span {
        float: right;
        font-size: 18px;
        font-weight: 600;;
      }
    }
    .info-content.task-percent {
      height: calc(100% - 58px);
      margin-top: 16px;
    }
  }
</style>
